home *** CD-ROM | disk | FTP | other *** search
/ Shareware Grab Bag / Shareware Grab Bag.iso / 007 / rfile.cq / rfile.c
Text File  |  1985-01-28  |  2KB  |  70 lines

  1. /*   This is a set of 3 general functions that will perform random            *
  2. *    file access.  `ropen()' opens a random file or creats it if it           *
  3. *    doesn't exist.  `hirec()' returns the high or last record in a           *
  4. *    file.  `rfile()' preforms the actual read/write operations.              *
  5. *    YOU MUST `close(port)' A FILE WHEN YOU ARE DONE.                         *
  6. *    EACH RECORD is a STRUCTURE of size `sz', that is `sz=sizeof(*data);'.    *
  7. *    `data' is the pointer to the record structure that has been              *
  8. *    loaded prior to a read, or where data is written into.                   *
  9. *    `rfiel()' returns the number of the record acted upon, should be         *
  10. *    the one you called UNLESS you called a recored number higher than        *
  11. *    the last record, then the actual record number is returned.              *
  12. *    See the comments in the text for more info.                              *
  13. */
  14.  
  15. /*   RFILE.C  Random file access functions  */
  16.  
  17. #include "ALL.H"    /* #defines O_RDWR = 2, O_CREAT = 0x0100 (hex)  */
  18.  
  19. int ropen(filspc)   /*  open file for random access  */
  20.  
  21. char *filspc;
  22.  
  23. { int port;
  24.  
  25.   port=open(filspc,O_RDWR | O_CREAT);
  26.   return(port);  /*  port<0 = error  */
  27. }
  28.  
  29.  
  30. int rfile(port,rec,data,sz,mode)   /*  random file access         *
  31.                                    *   assumes port assigned     */
  32. int port,rec;
  33. int sz;          /*  sizeof(structure)  */
  34. char *data;      /*  random record structure  */
  35. char mode;       /*  r = read, w = write  */
  36.  
  37. { int stat,read(),write(),lrec,hirec();
  38.   long pos,lseek();
  39.  
  40.   stat=0;
  41.   lrec=hirec(port,sz);
  42.   if(rec>lrec)   {  if(mode=='w')  rec=lrec+1;
  43.                     else rec=lrec;
  44.                  };
  45.   rec-=1;
  46.   pos=rec*sz;
  47.   lseek(port,pos,0);
  48.   switch(mode)   {  case'r':stat=read(port,data,sz);
  49.                             break;
  50.                     case'w':stat=write(port,data,sz);
  51.                             break;
  52.                  };
  53.   if(stat<=0) return(stat-1);   /* -1=EOF, <(-1)=error */
  54.   else return(rec+1);
  55. }
  56.  
  57.  
  58. int hirec(port,sz)   /*  random record count  */
  59.  
  60. int port;
  61. int sz;    /*  sizeof(structure)  */
  62.  
  63. { int ct;
  64.   long ef,lseek();
  65.  
  66.   ef=lseek(port,0L,2);
  67.   ct=ef/sz;
  68.   return(ct);
  69. }
  70.